#!bin/sh

function ios_upload_file()
{
    ftp_pwd=$1/$2
    echo cur_path=`pwd`
    if [ -d target ] && [ "x`ls target`" != "x" ];then
        echo upload files as follow:
        ls target
        echo create new folder "$ftp_pwd" at remote ftp server
        curl -u aolingli:ALL1234! ftp://192.168.8.251/output/$ftp_pwd/ --ftp-create-dirs  #创建远程文件夹
        cd target
        for upload_file in `ls`
        do
            echo upload_file=$upload_file
            curl -u aolingli:ALL1234! -T "$upload_file"  ftp://192.168.8.251/output/$ftp_pwd/
        done
        #不清楚mac上这样才能输出windows能识别的路径，但是能解决问题 ftp_path="\\\\\192.168.8.251\\\ftp\\output\\$1\\$2"
        echo ftp_path="ftp://192.168.8.251/output/$ftp_pwd/"
    else
        echo have no target or target is empty and will exit
        exit 1
    fi
}

function ios_sdk_build ()
{
        ios_scheme_tmp=$1
        [ -d Build ] && echo delete old Build dir && rm -rf Build
        echo ++++++++++++++++++++++scheme=$ios_scheme_tmp+++++++++++++++++++++++
        sdk_version=`xcodebuild -showsdks |grep "iphoneos" |awk -F '-sdk ' '{print $2}'`
        echo ++++++++++++++++++++++simulator version $sdk_version++++++++++++++++++++++
        xcodebuild  -scheme ${ios_scheme_tmp}  -configuration Release  -sdk $sdk_version clean build  #使用系统真机sdk构建
        [ $? -ne 0 ] && exit 1
        mv Build/Products Build/Products_re
        sdk_version=`xcodebuild -showsdks |grep "iphonesimulator" |awk -F '-sdk ' '{print $2}'`
        xcodebuild  -scheme ${ios_scheme_tmp}  -configuration Release  -sdk $sdk_version  clean build #使用模拟机sdk构建
        [ $? -ne 0 ] && exit 1
        ios_np=`pwd`
        mv Build/Products_re/* Build/Products/
        cd Build/Products
        echo os result:`ls`
        lipo -info Release-iphoneos/"$ios_scheme_tmp".framework/$ios_scheme_tmp #显示真机信息
        lipo -info Release-iphonesimulator/"$ios_scheme_tmp".framework/$ios_scheme_tmp #显示模拟机信息
        [ $? -ne 0 ] && exit 1
        cp Release-iphoneos/"$ios_scheme_tmp".framework/$ios_scheme_tmp ./
        lipo -create $ios_scheme_tmp Release-iphonesimulator/"$ios_scheme_tmp".framework/$ios_scheme_tmp -output Release-iphoneos/$ios_scheme_tmp #整合真机和模拟机
        [ $? -ne 0 ] && exit 1
        mv Release-iphoneos/$ios_scheme_tmp Release-iphoneos/"$ios_scheme_tmp".framework
        lipo -info Release-iphoneos/"$ios_scheme_tmp".framework/$ios_scheme_tmp |tee ios_result #显示整合后得信息
        sed -i .tmp 's/\n//g' ios_result #删除文件中的换行
        success_flag=`cat ios_result |awk -F ': ' '{print $3}'`   #检查是否整合成功
        echo ++++++++++++++++++++++++success_flag=$success_flag++++++++++++++++++++++++
        if [ "$ios_scheme_tmp" == "LBSREngine" ];then
            if [ "$success_flag" != "x86_64 arm64 " ];then #注意，结尾有空格
                echo LBSREngine build fail and is not x86_64 arm64
                exit 1
            else
                echo LBSREngine build success and is x86_64 arm64   #必须包含这四种类型才算整合成功
            fi
        else
            if [ "$success_flag" != "armv7 i386 x86_64 arm64 " ];then #注意，结尾有空格
                echo build fail and is not armv7 i386 x86_64 arm64
                exit 1
            else
                echo build success and is armv7 i386 x86_64 arm64   #必须包含这四种类型才算整合成功
            fi
        fi

        echo "===================copy file to ftp=========="
        cd Release-iphoneos/
        zip -q  -r "$ios_scheme_tmp"_framework.zip "$ios_scheme_tmp".framework
        cd $ios_np
        mv Build/Products/Release-iphoneos/"$ios_scheme_tmp"_framework.zip target/
        echo target files:
        ls target/
}
function ios_build ()
{
    #source /Users/jenkins/.bash_profile
    xcodebuild -list #显示scheme
    xcodebuild -showsdks #显示系统和模拟器得sdk版本
    echo "=================clean build================="
    [ -d target ] && echo "delete old target" && rm -rf target 
    [ -d Payload ] && echo "delete old Payload " && rm -rf Payload 
    mkdir target
    mkdir Payload

    #-configuration "Release" (default value)
    #-sdk iphoneos  (default use os sdk, can user xcodebuild -showsdks )
    app_name=$1
    ios_scheme=$1
    ios_type=$2
    echo now_path=`pwd`
    echo ======================building $ios_scheme $ios_type====================
    ios_app_name="$1"_"$ios_type"_Payload
    if [ "$ios_scheme" == "HPPlayTVAssistant" ];then #构建app
        mkdir arch
        archive_path=arch/${app_name}.xcarchive
        workspace_name=HPPlayTVAssistant
        # xcodebuild archive -workspace ${workspace_name}.xcworkspace -scheme ${app_name} -configuration $ios_type  clean build
        xcodebuild clean -workspace ${workspace_name}.xcworkspace -scheme ${app_name} -configuration $ios_type
        xcodebuild archive -workspace ${workspace_name}.xcworkspace -scheme ${app_name} -archivePath $archive_path -configuration $ios_type
        echo export ipa ....
        xcodebuild -exportArchive -archivePath $archive_path -exportPath arch/target_ipa  -exportOptionsPlist ${app_name}/${app_name}/Info.plist
        [ $? -ne 0 ] && exit 1
        echo "===================copy file to ftp=========="
        cp arch/target_ipa/${app_name}.ipa target/"$ios_app_name".ipa
    fi
    cur_repo_ios=`git remote -v | grep fetch |awk -F  "phoenix/" '{print $2}' |awk -F " " '{print $1}'` #AppleSenderSDK project
    cur_repo_mac=`git remote -v | grep fetch |awk -F  "ios/" '{print $2}' |awk -F " " '{print $1}'` # CastSdkMACVerisonForToB project
    if [ "$ios_scheme" == "AppleSenderSDK" -o  "$ios_scheme" == "LBLelinkKitSample" -o "$ios_scheme" == "OfficeMirroringSDK" -o "$ios_scheme" == "HPOfficeCastSDKMac" -o "$ios_scheme" == "LBCastToBDemo" -o "$ios_scheme" == "LBOfficeIPCastDemo" -o "$ios_scheme" == "LeBoCast" -o "$ios_scheme" == "SinaCast" -o "$ios_scheme" == "LBCastAssistant" -o  "$ios_scheme" == "AppleReplayKitSDK" ];then #构建sdk app
        #project_name="AppleSenderSDK"
        project_name=$ios_scheme
        [ "$ios_scheme" == "LBCastToBDemo" -o "$ios_scheme" == "AppleReplayKitSDK" ] && project_name="AppleSenderSDK"
        [ "$ios_scheme" == "LBOfficeIPCastDemo" ] && project_name="HPOfficeCastSDKMac"
        [ "$ios_scheme" == "LeBoCast" ] || [ "$ios_scheme" == "SinaCast" ] && project_name="SinaCast"
        [ "$ios_scheme" == "LBCastAssistant" ] && project_name="LBCastAssistant"
        [ "$ios_scheme" == "LBOfficeIPCastDemo" -a "$cur_repo_ios" == "AppleSenderSDK" ] && project_name="AppleSenderSDK"
        echo xcodebuild clean -project ${project_name}.xcodeproj -scheme ${app_name} -configuration $ios_type
        echo xcodebuild build -project ${project_name}.xcodeproj -scheme ${app_name} -configuration $ios_type
        xcodebuild clean -project ${project_name}.xcodeproj -scheme ${app_name} -configuration $ios_type
        xcodebuild build -project ${project_name}.xcodeproj -scheme ${app_name} -configuration $ios_type
        #xcodebuild archive -project ${project_name}.xcodeproj -scheme ${app_name} -configuration $ios_type  clean build
        [ $? -ne 0 ] && exit 1
        echo "===================copy file to ftp=========="
        if [ "$ios_scheme" == "HPOfficeCastSDKMac" -o "$ios_scheme" == "LeBoCast" -o "$ios_scheme" == "SinaCast" -o "$ios_scheme" == "LBCastAssistant" ] || [ "$ios_scheme" == "LBOfficeIPCastDemo" -a "$cur_repo_mac" == "CastSdkMACVerisonForToB" ] ;then
            mv Build/Products/$ios_type/"$app_name".app ./
            [ $? -ne 0 ] && exit 1
            mac_appname="$1"_"$ios_type"
            if [  "$ios_scheme" == "SinaCast" -o "$ios_scheme" == "LBCastAssistant" ]; then
                mkdir make_dmg
                echo path=`pwd`
                cp -rn BuildResource/* make_dmg/
                cp -rn "$app_name".app make_dmg/
		[  ! -f  "$app_name".xcodeproj/project.pbxproj ] && echo  "$app_name".xcodeproj/project.pbxproj not exist && exit 1
		d_version=`cat ./"$app_name".xcodeproj/project.pbxproj |grep MARKETING_VERSION |awk -F " = " '{print $2}' |awk -F ";" '{print $1}' |sed -n 1p`
		d_bid=`cat ./"$app_name".xcodeproj/project.pbxproj |grep PRODUCT_BUNDLE_IDENTIFIER |awk -F " = " '{print $2}' |awk -F ";" '{print $1}' |sed -n 1p`
                cd make_dmg
                app_notarize_dmg  "$app_name" "$d_bid" "$d_version" # $1:app name $2:bundle id $3:version
                cd ../
                mv make_dmg/*.dmg target/
            fi
            zip -q -r "$mac_appname".zip "$app_name".app
            cp "$mac_appname".zip target/"$mac_appname".zip
        else
            mv Build/Products/$ios_type-iphoneos/"$app_name".app Payload/
            [ $? -ne 0 ] && exit 1
            zip -q -r "$ios_app_name".zip Payload
            cp "$ios_app_name".zip target/"$ios_app_name".ipa
        fi
    fi

    if [ "$ios_scheme" == "HPOfficeCastWork" ] || [ "$ios_scheme" == "LBOfficeIPCast" -a "$cur_repo_mac" == "CastSdkMACVerisonForToB" ];then #构建mac sdk
        mac_path=`pwd`
        xcodebuild  -scheme ${ios_scheme}  -configuration $ios_type  clean
        xcodebuild  -scheme ${ios_scheme}  -configuration $ios_type  build
        [ $? -ne 0 ] && exit 1
    fi
    #构建 ios sdk
    if [ "$ios_scheme" == "HPCastLink" -o "$ios_scheme" == "LBLelinkKit" -o "$ios_scheme" == "HPOfficeCast_LBSREngine" ] ||  [ "$ios_scheme" == "LBOfficeIPCast"  -a "$cur_repo_ios" == "AppleSenderSDK"  ];then
        if [ "$ios_scheme" == "HPOfficeCast_LBSREngine" -o "$ios_scheme" == "LBOfficeIPCast" ]; then
           [ "$ios_scheme" == "HPOfficeCast_LBSREngine" ] && ios_sdk_build HPOfficeCast
           [ "$ios_scheme" == "LBOfficeIPCast" ] && ios_sdk_build LBOfficeIPCast
           ios_sdk_build LBSREngine
           cd target
	       if [ "$ios_scheme" == "HPOfficeCast_LBSREngine" ];then
               unzip HPOfficeCast_framework.zip
	       unzip LBSREngine_framework.zip
               rm HPOfficeCast_framework.zip LBSREngine_framework.zip
               zip -q -r HPOfficeCast_LBSREngine_framework.zip *
	       fi
           if [ "$ios_scheme" == "LBOfficeIPCast" ];then
               unzip LBOfficeIPCast_framework.zip
               unzip LBSREngine_framework.zip
               rm LBOfficeIPCast_framework.zip LBSREngine_framework.zip
               zip -q -r LBOfficeIPCast_LBSREngine_framework.zip *
           fi
           rm -rf *.framework
           cd ../
        else
           ios_sdk_build $ios_scheme
        fi
    fi
    echo ios mac target files: `ls target`
 }

function app_notarize_dmg()
{

    echo sign $1 app and get dmg
    dapp_name="$1"
    info_file=info_notarize
    p_bundle_id=$2
    dapp_version=$3
    echo app:$dapp_name, bundle id:$p_bundle_id,version:$dapp_version
    
    [ -f $info_file ] && echo delete old info file && rm $info_file
    touch $info_file
    echo you must unlock your keychain, or sigin will get error:errSecInternalComponent
    security unlock-keychain -p "1234567890" ~/Library/Keychains/login.keychain
    
    security find-identity -v > $info_file
    cert_file=`cat $info_file |grep "Developer ID Application" |awk -F "\"" '{print $2}'`
    echo cert_file=$cert_file

    echo ========signing mac app ==========
    codesign -f -s "$cert_file" -v "$dapp_name".app --deep

    echo ========checking signed ========
    spctl --verbose=4 --assess --type execute "$dapp_name".app > $info_file
    sign_result=`cat $info_file |grep accepted `
    #[ "x$sign_result" == "x" ] && echo "sign result is not accepted" && exit 1 

    echo ======make app to zip=======
    ditto -c -k --keepParent "$dapp_name".app  signed_"$dapp_name".zip

    echo =======notarize app======
    u_name="zx@hpplay.cn"
    u_passwd="ldlv-ckhj-aooj-zepb"
    asc_provider="7R34852FKA" #xcrun altool --list-providers -u "zx@hpplay.cn" -p "ldlv-ckhj-aooj-zepb"
    echo  "need some time ....."
    xcrun altool --notarize-app \
                 --primary-bundle-id "$p_bundle_id" \
                 --username "$u_name" \
                 --password "$u_passwd" \
                 --asc-provider "$asc_provider" \
                 --file signed_"$dapp_name".zip   > $info_file
    n_uuid=`cat $info_file |grep -rn "RequestUUID" |awk -F " = " '{print $2}' `
    echo n_uuid=$n_uuid

    echo sleep 120s to wait notarize....
    sleep 120
    echo =============get notarize info by uuid===========
    echo xcrun altool --notarization-info "$n_uuid" --username "$u_name" --password "$u_passwd"
    xcrun altool --notarization-info "$n_uuid" --username "$u_name" --password "$u_passwd"

    echo =============stapler zip===============
    xcrun stapler staple -v signed_"$dapp_name".zip

    echo =============checking  app===============
    rm  -rf $dapp_name.app 
    [ -d "$dapp_name".app ] && echo delete $dapp_name.app failed && exit 1
    ls
    unzip -q signed_"$dapp_name".zip 
    #xcrun stapler staple -v $dapp_name.app #have no need staple again
    spctl -a -v $dapp_name.app > $info_file && cat $info_file
    echo `pwd`
    result_is=`cat $info_file |grep -i "Notarized"`
    #[ "x$result_is" == "x" ] && echo "notarized failed !!" && exit 1

    echo ==============make dmg =========
    appdmg appdmg.json "$dapp_name"_"$dapp_version".dmg

}

echo jenkins var as follow:
echo build_num=$BUILD_NUMBER
echo build_user_id=$BUILD_USER_ID
echo build_user=$BUILD_USER
echo job_name=$JOB_NAME
trigger_user=$BUILD_USER_ID

ph_channel=$1
ph_type=$2
ph_branch_tmp=$3
ph_repo=$4
ph_tag=$5
echo config: ph_channel=$ph_channel,ph_type=$ph_type,ph_branch_tmp=$ph_branch_tmp,ph_repo=$ph_repo,ph_tag=$ph_tag

if [ "x$ph_tag" != "x" ];then #如果输入tag,优先使用tag
    if [ "x`git tag |grep $ph_tag`" == "x" ];then #判断tag是否存在
        echo have no this tag:$ph_tag and please check again as follow:
        git tag
        exit 1
    else
        echo have input tag:$ph_tag
    fi
    git checkout $ph_tag
    ph_branch_tmp=$ph_tag
else  #如果没有输入tag,则使用分支
    git checkout $ph_branch_tmp
    git pull
fi

ph_branch=`echo $ph_branch_tmp |sed 's/\.//g'`
now_time=`date "+%Y%m%d%H%M"`
commit=`git rev-parse --short HEAD`
now_time="$now_time"_"$ph_branch"_"$commit"_"$ph_type"_"$trigger_user"

echo =============building $ph_repo===========
if [ "$ph_repo" == "ios_app" ];then
    ph_ftp_dir=phoenix_ios_app
    ios_build HPPlayTVAssistant $ph_type  #构建ios ipa
fi
if [ "$ph_repo" == "ios_sdk" ];then
    ph_ftp_dir=phoenix_ios
    if [ "$ph_channel" == "LBLelinkKitSample" ];then
         cd LBLelinkKitSample
    else
        cd AppleSenderSDK
    fi
    [ "$ios_scheme" == "LBLelinkKit" -a "$ph_type" == "Release" ] && cp -rn ../LBLelinkKitSample ./
    ios_build $ph_channel $ph_type
    #ios_build $ph_channel Release
    if [ "$ios_scheme" == "LBLelinkKit" -a "$ph_type" == "Release" ];then
           zip -q -r target/LBLelinkKit_framework.zip ../LBLelinkKitSample
           cp -rn target target_bak
           ios_build AppleSenderSDK Release
           mv target_bak/* target/
           du -sh target/*
    fi
fi

if [ "$ph_repo" == "ios_tob_sdk" ];then
    ph_ftp_dir=CastSdkIOSVerisonForToB
    cd OfficeMirroringSDKNew
    ios_build $ph_channel $ph_type
fi
if [ "$ph_repo" == "mac_tob_sdk" ];then
    ph_ftp_dir=CastSdkMACVerisonForToB
    if [ $ph_channel == "LeBoCast" -o $ph_channel == "SinaCast" ];then
          cd SinaCast
    else 
    	if [ $ph_channel == "LBCastAssistant" ];then 
          	cd LBCastAssistant
   	 else
          	cd HPOfficeCastSDKMac
   	 fi
    fi
    if [ "$ph_channel" == "HPOfficeCastWork" -o "$ph_channel" == "LBOfficeIPCast" ];then  #mac sdk 的构建存在真机模拟机的区分 
       echo olny release verison SDK need to build debug and release toghter
       [ "$ph_channel" == "HPOfficeCastWork" -o  "$ph_channel" == "LBOfficeIPCast" ] && [ "$ph_type" == "Release"  ] &&  cp -rn ../HPOfficeCastKitDemo ./
       ios_build $ph_channel $ph_type
       mv Build/Products/$ph_type ./
       #ios_build $ph_channel Debug
       #mv Build/Products/Debug ./
       #ftp release path also need a demo package when MAC sdk release,but need to replace building sdk into this demo package
       if [ "$ph_channel" == "HPOfficeCastWork" -o "$ph_channel" == "LBOfficeIPCast" ] && [ "$ph_type" == "Release" ] ; then 
           rm -rf ./HPOfficeCastKitDemo/HPOfficeCastMacDemo/HPOfficeCastWork.framework
           rm -rf ./HPOfficeCastKitDemo/HPOfficeCastMacDemo/HPOfficeCastResources.bundle
           cp -rn Release/* ./HPOfficeCastKitDemo/HPOfficeCastMacDemo
           ls ./HPOfficeCastKitDemo/HPOfficeCastMacDemo
           zip -q -r  HPOfficeCastKitDemo.zip HPOfficeCastKitDemo
           mv HPOfficeCastKitDemo.zip target/
       fi
       zip -q  -r "$ph_channel"_framework.zip  $ph_type
       mv "$ph_channel"_framework.zip target/
       if [ "$ph_channel" == "HPOfficeCastWork" -o "$ph_channel" == "LBOfficeIPCast" ] && [ "$ph_type" == "Release" ] ; then 
           cp -rn  target target_bak
           echo target_bak files:
           ls target_bak
           echo =============building MAC App=======
           #ftp release path also need a mac app package when MAC sdk release
           ios_build HPOfficeCastSDKMac Release
           mv target_bak/* target/
       fi
    else
       ios_build $ph_channel $ph_type
    fi
fi
if [ "$ph_repo" == "ios_dingding_sdk" ];then
    ph_ftp_dir=CastSdkIOSVerisonForDingDing
    ios_build $ph_channel $ph_type
fi
ios_upload_file $ph_ftp_dir $now_time #上传构建结果到ftp上
